package com.lyb.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyb.spzx.common.exception.DefinedException;
import com.lyb.spzx.manager.constant.CacheConstant;
import com.lyb.spzx.manager.mapper.SysUserMapper;
import com.lyb.spzx.manager.service.SysUserService;
import com.lyb.spzx.model.dto.system.LoginDto;
import com.lyb.spzx.model.dto.system.SysUserDto;
import com.lyb.spzx.model.dto.system.system.SysUser;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import com.lyb.spzx.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper mapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public LoginVo login(LoginDto loginDto) {

        String codeKey = loginDto.getCodeKey();
        String captcha = loginDto.getCaptcha();
        String redisCode = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + codeKey);
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)){
            throw new DefinedException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //通过验证删除redis中的验证码
        redisTemplate.delete(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + codeKey);

        SysUser sysUser = mapper.selectByUsername(loginDto.getUserName());
        if (sysUser == null){
            throw new DefinedException(ResultCodeEnum.LOGIN_ERROR);
        }

        String inputPassword = loginDto.getPassword();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if (!md5DigestAsHex.equals(sysUser.getPassword())){
            throw new DefinedException(ResultCodeEnum.LOGIN_ERROR);
        }

        //生成token 保存到redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        //将生成的token存储到redis中 TODO 将来改回30分钟
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_PREFIX + token
                , JSON.toJSONString(sysUser),300000, TimeUnit.MINUTES);

        //构建响应结果
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

    @Override
    public PageInfo<SysUser> findUserByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> userList = mapper.findUserByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public void loginout(String token) {
        redisTemplate.delete(CacheConstant.USER_LOGIN_PREFIX +token);
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setIsDeleted(0);
        sysUser.setStatus(1);
        mapper.saveSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUser.setUpdateTime(new Date());
        mapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteUserById(Integer id) {
        mapper.deleteById(id);
    }
}
